/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package appmanager.server.appstore.runner;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.logging.Logger;

import appmanager.server.tools.HashUtilities;

import cumulusCloud.common.InformationPath;

import sllib.xmltojava.XmlToJavaListAnnotation;
import sllib.xmltojava.XmlToJavaProcessor;

public class InstallRun extends Downloader {
	private static Logger logger = Logger.getLogger(UpdateAppListRun.class.getName());
	private String webname;
	private String hash;
	
	private XmlToJavaListAnnotation urlListAnnotation = new XmlToJavaListAnnotation() {
		@Override
		public Class<? extends Annotation> annotationType() {
			return XmlToJavaListAnnotation.class;
		}

		@Override
		public Class<String> value() {
			return String.class;
		}
	};

	public InstallRun(String webname, String hash) {
		this.webname = webname;
		this.hash = hash;
	}

	@Override
	public String getName() {
		return "Installing " + webname;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		logger.info("Starting to install " + webname);
		
		// Retrieve urls
		logger.info("Retrieve urls for " + webname);
		setStatus("Getting urls");
		File urlFile;
		try {
			urlFile = File.createTempFile("url", null);
		} catch (IOException e) {
			e.printStackTrace();
			setFinalStatus("ERROR creating temp urls file");
			return;
		}
		if (!downloadUrl("http://cumuluscloudappstore.appspot.com/GetUrl/" + webname, urlFile, 10)) {
			setFinalStatus("ERROR getting urls");
			return;
		}
		
		// Parse Urls
		logger.info("Parsing the urls file");
		setStatus("Loading the urls file");
		List<String> urls;
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(urlFile);
			urls = XmlToJavaProcessor.parseXml(fin, List.class, urlListAnnotation);
		} catch (Exception e) {
			e.printStackTrace();
			setFinalStatus("ERROR could not parse url file");
			return;
		} finally {
			try {
				fin.close();
			} catch (Exception e) {
			}
		}
		urlFile.delete();
		
		// Retrieve war
		logger.info("Retrieve war file for " + webname);
		setStatus("Downloading the webapp");
		File warFile;
		try {
			warFile = File.createTempFile("war", null);
		} catch (IOException e) {
			e.printStackTrace();
			setFinalStatus("ERROR creating temp war file");
			return;
		}
		if (!downloadUrl(urls, warFile, 3)) {
			setFinalStatus("ERROR getting war");
			return;
		}
		
		// Check if the war is valid
		String curHash = HashUtilities.hash(warFile);
		if (!hash.equals(curHash)) {
			logger.severe("Expected hash:\n" + hash + "\nCurrent hash:\n" + curHash);
			setFinalStatus("ERROR downloaded war file is not valid");
			return;
		}
		
		// Copy war to the webapp folder
		logger.info("Moving the war to the webapp folder for " + webname);
		File destination = new File(InformationPath.getCloudAppsInstallPath() + webname + ".war");
		destination.delete();
		if (warFile.renameTo(destination)) {
			setFinalStatus("SUCCESS");
		} else {
			setFinalStatus("ERROR could not move the war file to destination");
		}
	}
}
